package net.mhelvens.deltaprofiles;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class RuleEditGeneralFragment extends Fragment {
	@SuppressWarnings("unused")
	private static final String TAG = RuleEditGeneralFragment.class.getSimpleName();

	final static public int REQUEST_EDIT_LOWER_PRIORITY_RULE = 1;
	
	final private Rule mRule;
	
	private EditText    mName;
	private EditText    mDescription;
	private ImageView   mImageButton;
	
	private TextView    mPriorityText;
	private ImageButton mAddPriorityButton;
	private View        mPriorityHrule;
	private ListView    mPriorityList;

	private Rule.Adapter mAllRulesICouldGetPriorityOver;
	private Rule.Adapter mAllRulesIHavePriorityOver;
	
	RuleEditGeneralFragment(Rule rule) { mRule = rule; }
	
	public void collectViews() {
		mName              = (EditText)    getView().findViewById(R.id.name             );
		mDescription       = (EditText)    getView().findViewById(R.id.description      );
		mImageButton       = (ImageView)   getView().findViewById(R.id.imageButton      );
		mPriorityText      = (TextView)    getView().findViewById(R.id.priority_text    );
		mAddPriorityButton = (ImageButton) getView().findViewById(R.id.addPriorityButton);
		mPriorityHrule     =               getView().findViewById(R.id.priority_hrule   );
		mPriorityList      = (ListView)    getView().findViewById(R.id.priorityList     );
	}
	
	public void setupViews() {
		mName.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			} // intentionally empty
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			} // intentionally empty
			
			public void afterTextChanged(Editable s) {
				mRule.setName(s.toString());
			}
		});

		mDescription.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			} // intentionally empty
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			} // intentionally empty
			
			public void afterTextChanged(Editable s) {
				mRule.setDescription(s.toString());
			}
		});
		
		mImageButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO
			}
		});
		
		mPriorityList.setOnItemClickListener(new ListView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> av, View v, int i, long id) {
				startActivityForResult(
					new Intent(RuleEditActivity.EDIT_RULE, null, getActivity(), RuleEditActivity.class)
						.putExtra("id", id),
					REQUEST_EDIT_LOWER_PRIORITY_RULE
				);
			}
		});
		
		mAddPriorityButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final DialogFragment df = (new DialogFragment() {
					public void dismissMe() { dismiss(); }
					public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
				        ListView lv = (ListView) inflater.inflate(R.layout.rule_edit_general_add_priority, container, false);
				        lv.setAdapter(mAllRulesICouldGetPriorityOver);
				        lv.setOnItemClickListener(new ListView.OnItemClickListener() {
							public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long chosenID) {
								mRule.grantPriorityOver(chosenID);
								dismissMe();
								refreshPriorityList();
							}
						});
				        getDialog().setTitle(getResources().getString(R.string.grant_priority_over));
				        return lv;
				    }
				});
				df.show(getChildFragmentManager(), "add-priority-list");
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_EDIT_LOWER_PRIORITY_RULE) {
			if (resultCode == RuleEditActivity.RESULT_OK || resultCode == RuleEditActivity.RESULT_DELETED)
				refreshPriorityList();
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	public void refreshPriorityList() {
		mPriorityList.setAdapter(mRule.allRulesIHavePriorityOver(
			Rule.Adapter.FLAG_NAME          |
			Rule.Adapter.FLAG_DELETE_BUTTON |
			Rule.Adapter.FLAG_ICON
		).setOnDeleteClickListener(new Rule.Adapter.OnRuleViewDeleteClickListener() {
			public void onDeleteClick(Rule rule) {
				mRule.revokePriorityOver(rule.id());
				refreshPriorityList();
			}
		}));
		
		mAllRulesIHavePriorityOver     = (Rule.Adapter) mPriorityList.getAdapter();
        mAllRulesICouldGetPriorityOver = mRule.allRulesICouldGetPriorityOver(
        	Rule.Adapter.FLAG_NAME |
        	Rule.Adapter.FLAG_ICON
        );
        
		// Refresh priority list height
		//
		LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mPriorityList.getLayoutParams();
		layoutParams.height = 0;
		if (mAllRulesIHavePriorityOver.getCount() > 0) {
			View v = mPriorityList.getAdapter().getView(0, null, null);
			v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
			layoutParams.height = mAllRulesIHavePriorityOver.getCount() * v.getMeasuredHeight();
		}
        mPriorityList.setLayoutParams(layoutParams);
        
        // Refresh priority list text and hrule
        //
        if (mAllRulesIHavePriorityOver.getCount() == 0) {
        	if (mAllRulesICouldGetPriorityOver.getCount() == 0)
            	mPriorityText.setText(getResources().getString(R.string.cant_have_priorities));
            else
	        	mPriorityText.setText(getResources().getString(R.string.no_priorities));
        	mPriorityHrule.setVisibility(View.GONE);
        } else  {
        	mPriorityText.setText(getResources().getString(R.string.has_priority_over));
        	mPriorityHrule.setVisibility(View.VISIBLE);
        }
        
        // (Show / hide 'add priority' button
        //
    	mAddPriorityButton.setVisibility(
    		mAllRulesICouldGetPriorityOver.getCount() > 0 ? View.VISIBLE : View.GONE
    	);
	}
	
	public void refreshViews() {
		mName       .setText(mRule.name());
		mDescription.setText(mRule.description());
		if (mRule.icon() != null)
			mImageButton.setImageResource(mRule.icon());
		refreshPriorityList();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.rule_edit_general, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		
		collectViews();
		setupViews();
		refreshViews();
	}
	
	
	
}
